package fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jhyj.shop.R;
import java.io.File;
import base.BaseFragment;

/**
 * 首页的fragment
 * author:wbin
 * 2016.01.23
 */
public class Home_Fragment extends BaseFragment {
    private WebView webview_home;
    private ProgressBar pb_progressbar;
    private TextView tv_loading;  
    private LinearLayout ll_progressbar;
    private static final String APP_CACHE_DIRNAME = "/webcache"; // web缓存目录
    private String url ="http://223.71.241.125:8081/m"; // 网页url
    @Override
    protected View initView() {
        View view = View.inflate(activity, R.layout.fragment_home, null);
        pb_progressbar = (ProgressBar) view.findViewById(R.id.pb_progressbar);
        tv_loading = (TextView) view.findViewById(R.id.tv_loading);
        ll_progressbar = (LinearLayout) view.findViewById(R.id.ll_progressbar);

        webview_home = (WebView) view.findViewById(R.id.webview_home);

        initWebView();
        ll_progressbar.setVisibility(view.VISIBLE);
        return view;
    }

    /**
     * 初始化webview
     */
    private void initWebView() {
    	clearWebViewCache();
        webview_home.getSettings().setJavaScriptEnabled(true);  //设置WebView支持javascript
        webview_home.getSettings().setUseWideViewPort(true);    //设置是当前html界面自适应屏幕
        webview_home.getSettings().setSupportZoom(true);
        webview_home.getSettings().setBuiltInZoomControls(true); //设置支持缩放
        webview_home.getSettings().setLoadWithOverviewMode(true);
        webview_home.getSettings().setDefaultTextEncodingName("UTF-8");
        webview_home.requestFocus();
        webview_home.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT,无网络时，使用LOAD_CACHE_ELSE_NETWORK
        webview_home.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 设置缓存模式
        // 开启DOM storage API 功能
        webview_home.getSettings().setDomStorageEnabled(true);
        // 开启database storage API功能
        webview_home.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = activity.getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
        Log.i("cachePath", cacheDirPath);
        // 设置数据库缓存路径
        webview_home.getSettings().setDatabasePath(cacheDirPath); // API 19 deprecated
        // 设置Application caches缓存目录
        webview_home.getSettings().setAppCachePath(cacheDirPath);
        // 开启Application Cache功能
        webview_home.getSettings().setAppCacheEnabled(true);

         webview_home.loadUrl(url);
        //在webview中打开链接而不会跳转到外部浏览器
         webview_home.setWebViewClient(new WebViewClient()
        {
            @Override
            public void onLoadResource(WebView view, String url)
            {
                Log.i("TAG", "onLoadResource url=" + url);

                super.onLoadResource(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }else{
                    webview_home.loadUrl(url);
                }
                return true;
            }

            // 页面开始时调用
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                Log.e("TAG", "onPageStarted");
                super.onPageStarted(view, url, favicon);
            }

            // 页面加载完成调用
            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                ll_progressbar.setVisibility(view.INVISIBLE);
            }
            //页面加载出错
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Toast.makeText(activity, "亲，没网，请重新咻咻网络哦！", Toast.LENGTH_SHORT).show();

            }
    });
         
         webview_home.setOnKeyListener(new View.OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				 if (event.getAction() == KeyEvent.ACTION_DOWN) {
					 if(keyCode==KeyEvent.KEYCODE_BACK&&webview_home.canGoBack()){
						 webview_home.goBack();
						 return true;
					 }
				 }
				return false;
			}
		});
}

    public void clearWebViewCache() {
        // 清理WebView缓存数据库
        try {
//            deleteDatabase("webview.db");
//            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // WebView缓存文件
        File appCacheDir = new File(activity.getFilesDir().getAbsolutePath()
                + APP_CACHE_DIRNAME);
        Log.e("TAG", "appCacheDir path=" + appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(activity.getCacheDir().getAbsolutePath()
                + "/webviewCache");
        Log.e("TAG", "appCacheDir path=" + webviewCacheDir.getAbsolutePath());

        // 删除webView缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        // 删除webView缓存，缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    public void deleteFile(File file) {
        Log.i("TAG", "delete file path=" + file.getAbsolutePath());
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e("TAG", "delete file no exists " + file.getAbsolutePath());
        }
    }
    
    
}


